from django.contrib.auth import authenticate, login
from django.http import HttpResponse
from django.shortcuts import render_to_response, get_object_or_404
from django.http import HttpResponseRedirect
from django.contrib.auth.models import User
from django.template import RequestContext
from django import forms
from django.core.urlresolvers import reverse
from django.contrib.sitemaps import Sitemap
from datetime import datetime, timedelta
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from fblaproj.accounts.models import UserProfile
from fblaproj.panel.models import UserGalleryImages, Message, UserGallery
from django.forms.fields import email_re
import re
from fblaproj.socialgraph.models import UserLink
from fblaproj.socialgraph.util import get_people_user_follows, get_people_following_user
from django.db.models import Q
from django.template.defaultfilters import slugify
from array import array
from search import *
class PictureUploadForm(forms.ModelForm):
   	class Meta:
		model = UserGalleryImages
		fields = ('title', 'description', 'image')
@login_required
def EditImage(request, user_name, gallery_id, image_id):
	if not request.user.is_staff:
		if (request.user.username != user_name):
			return HttpResponseRedirect('http://fblaconnection.com/panel/'+ request.user.username + '/')
	try:
		user = User.objects.get(username=user_name)
	except User.DoesNotExist:
		return HttpResponseRedirect('http://fblaconnection.com/panel/'+ request.user.username + '/')
	try:
		ugallery = UserGallery.objects.get(pk=gallery_id)
	except UserGallery.DoesNotExist:
		return HttpResponseRedirect('http://fblaconnection.com/panel/'+ request.user.username + '/')
	images = get_object_or_404(UserGalleryImages, pk=image_id)
	if not request.user.is_staff:
		if (user != request.user):
			own = False
		else:
			own = True
	else:
		own = True
		
	title = images.title
	description = images.description
	context = {
		'user' : user,
		'ugallery' : ugallery,
		'images' : images,
		'title' : title,
		'description' : description,
		'own' : own,
	}
	if request.POST:
		if request.POST.get('save'):
			title = request.POST['title']
			description = request.POST['description']
			#Errors
			errors = False
			title_error = False
			description_error = False
			if (title == ""):
				errors = True
				title_error = True
			if (description == ""):
				description_error = True
				errors = True
			if errors:
				context.update({
					'errors' : errors,
					'title_error' : title_error,
					'description_error' : description_error,
					'title' : title,
					'description' : description,
				})
			else:
				images.title = title
				images.description = description
				images.save()
				success = True
				title = images.title
				description = images.description
				context.update({
					'success' : success,
					'title' : title,
					'description' : description,
					
				})
	if request.GET:
		if request.GET.get('ex'):
			ex = request.GET['ex']
			context.update({
				'ex' : ex,
			})
			if (ex == 'delete'):
				images.delete()
				return HttpResponseRedirect('http://fblaconnection.com/panel/'+ request.user.username + '/gallery/' + ugallery.slug + '/')
	return render_to_response('panel/panel_gallery_image_edit.html', context,  context_instance = RequestContext(request))
@login_required
def NewImage(request, user_name, gallery_id):
	if not request.user.is_staff:
		if (request.user.username != user_name):
			return HttpResponseRedirect('http://fblaconnection.com/panel/'+ request.user.username + '/')
	try:
		user = User.objects.get(username=user_name)
	except User.DoesNotExist:
		return HttpResponseRedirect('http://fblaconnection.com/panel/'+ request.user.username + '/')
	try:
		ugallery = UserGallery.objects.get(pk=gallery_id)
	except UserGallery.DoesNotExist:
		return HttpResponseRedirect('http://fblaconnection.com/panel/'+ request.user.username + '/')
	context = {
		'user' : user,
		'ugallery' : ugallery,
	}
	if request.POST:		
		form = PictureUploadForm(request.POST, request.FILES, instance=UserGalleryImages(ugallery=ugallery))
		title = request.POST['title']
		description = request.POST['description']
		context.update({
			'form' : form,
			'title' : title,
			'description' : description,
		})
		if form.is_valid():
			form.save()
			success = True
			context.update({
				'success' : success,
			})
	else:
		form = PictureUploadForm(instance=UserGalleryImages(ugallery=ugallery))
		context.update({
			'form' : form,
		})
	return render_to_response('panel/panel_gallery_image_new.html', context,  context_instance = RequestContext(request))
@login_required
def EditGallery(request, user_name, gallery_id):
	if not request.user.is_staff:
		if (request.user.username != user_name):
			return HttpResponseRedirect('http://fblaconnection.com/panel/'+ request.user.username + '/')
	try:
		user = User.objects.get(username=user_name)
	except User.DoesNotExist:
		return HttpResponseRedirect('http://fblaconnection.com/panel/'+ request.user.username + '/')
	try:
		ugallery = UserGallery.objects.get(pk=gallery_id)
	except UserGallery.DoesNotExist:
		return HttpResponseRedirect('http://fblaconnection.com/panel/'+ request.user.username + '/')
	title = ugallery.title
	description = ugallery.description
	context = {
		'user' : user,
		'title' : title,
		'ugallery' : ugallery,
		'description' : description,
	}
	if request.POST:
		if (request.POST.get('save')):
			title = request.POST['title']
			description = request.POST['description']
			#Errors
			errors = False
			title_error = False
			description_error = False
			context.update({
				'title' : title,
				'description' : description,
			})
			if (title == ""):
				errors = True
				title_error = True
			if (description == ""):
				errors = True
				description_error = True
			if errors:
				context.update({
					'errors' : errors,
					'title_error' : title_error,
					'description_error' : description_error,
				})
				return render_to_response('panel/panel_gallery_edit.html', context,  context_instance = RequestContext(request))
			else:
				ugallery.title = title
				ugallery.description = description
				ugallery.save()
				success = True
				context.update({
					'success' : success,
					'ugallery' : ugallery,
				})
	if request.GET:
		if request.GET.get('ex'):
			ex = request.GET['ex']
			context.update({
				'ex' : ex,
			})
			if (ex == 'delete'):
				ugallery.delete()
				return HttpResponseRedirect('http://fblaconnection.com/panel/'+ request.user.username + '/gallery/')
	return render_to_response('panel/panel_gallery_edit.html', context,  context_instance = RequestContext(request))
@login_required
def NewGallery(request, user_name):
	if not request.user.is_staff:
		if (request.user.username != user_name):
			return HttpResponseRedirect('http://fblaconnection.com/panel/'+ request.user.username + '/')
	try:
		user = User.objects.get(username=user_name)
	except User.DoesNotExist:
		return HttpResponseRedirect('http://fblaconnection.com/panel/'+ request.user.username + '/')
	context = {
		'user' : user,
	}
	if request.POST:
		if (request.POST.get('save')):
			title = request.POST['title']
			description = request.POST['description']
			#Errors
			errors = False
			title_error = False
			description_error = False
			context.update({
				'title' : title,
				'description' : description,
			})
			if (title == ""):
				errors = True
				title_error = True
			if (description == ""):
				errors = True
				description_error = True
			if errors:
				context.update({
					'errors' : errors,
					'title_error' : title_error,
					'description_error' : description_error,
				})
				return render_to_response('panel/panel_gallery_new.html', context,  context_instance = RequestContext(request))
			else:
				ugallery = UserGallery(title=title, description=description, owner=user)
				ugallery.save()
				success = True
				context.update({
					'success' : success,
					'ugallery' : ugallery,
				})
	return render_to_response('panel/panel_gallery_new.html', context,  context_instance = RequestContext(request))
@login_required
def GalleryDisp(request, user_name, gallery_slug):
	try:
		user = User.objects.get(username=user_name)
	except User.DoesNotExist:
		return HttpResponseRedirect('http://fblaconnection.com/panel/'+ request.user.username + '/')
	ugallery = get_object_or_404(UserGallery, slug__iexact=gallery_slug)
	images = UserGalleryImages.objects.filter(ugallery=ugallery)
	if not request.user.is_staff:
		if (user != request.user):
			own = False
		else:
			own = True
	else:
		own = True
	context = {
		'user' : user,
		'ugallery' : ugallery,
		'images' : images,
		'own' : own,
	}
	if request.GET:
		if request.GET.get('gallery'):
			slideshow = request.GET['gallery']
			if (slideshow == 'true'):
				return render_to_response('panel/panel_gallery_slide.html', context,  context_instance = RequestContext(request))
			else:
				slideshow = None
	return render_to_response('panel/panel_gallery_view.html', context,  context_instance = RequestContext(request))
@login_required
def GalleryImageDisp(request, user_name, gallery_slug, img_slug):
	try:
		user = User.objects.get(username=user_name)
	except User.DoesNotExist:
		return HttpResponseRedirect('http://fblaconnection.com/panel/'+ request.user.username + '/')
	ugallery = get_object_or_404(UserGallery, slug__iexact=gallery_slug)
	images = get_object_or_404(UserGalleryImages, slug__iexact=img_slug)
	if (images.ugallery != ugallery):
		return HttpResponseRedirect('http://fblaconnection.com/panel/'+ request.user.username + '/')
	if not request.user.is_staff:
		if (user != request.user):
			own = False
		else:
			own = True
	else:
		own = True
	context = {
		'user' : user,
		'ugallery' : ugallery,
		'images' : images,
		'own' : own,
	}
	return render_to_response('panel/panel_gallery_view_img.html', context,  context_instance = RequestContext(request))
@login_required
def Gallery(request, user_name):
	try:
		user = User.objects.get(username=user_name)
	except User.DoesNotExist:
		return HttpResponseRedirect('http://fblaconnection.com/panel/'+ request.user.username + '/')
	ugallery = UserGallery.objects.filter(owner=user).order_by('-date_added')
	images = UserGalleryImages.objects.all()
	if not request.user.is_staff:
		if (user != request.user):
			own = False
		else:
			own = True
	else:
		own = True
	context = {
		'user' : user,
		'ugallery' : ugallery,
		'images' : images,
		'own' : own,
	}
	return render_to_response('panel/panel_gallery.html', context,  context_instance = RequestContext(request))
@login_required
def MessageView(request, user_name):
	if not request.user.is_staff:
		if (request.user.username != user_name):
			return HttpResponseRedirect('http://fblaconnection.com/panel/' + request.user.username + '/')
	try:
		user = User.objects.get(username=user_name)
	except User.DoesNotExist:
		return HttpResponseRedirect('http://fblaconnection.com/panel/'+ request.user.username + '/')
	message = Message.objects.filter(reciever=user)
	profile = user.get_profile()
	
	context = {
		'user' : user,
		'profile' : profile,
		'message' : message,
	}
	return render_to_response('panel/panel_message_index.html', context,  context_instance = RequestContext(request))
@login_required
def MessageViewSent(request, user_name):
	if not request.user.is_staff:
		if (request.user.username != user_name):
			return HttpResponseRedirect('http://fblaconnection.com/panel/' + request.user.username + '/')
	try:
		user = User.objects.get(username=user_name)
	except User.DoesNotExist:
		return HttpResponseRedirect('http://fblaconnection.com/panel/'+ request.user.username + '/')
	message = Message.objects.filter(sender=user)
	profile = user.get_profile()
	context = {
		'user' : user,
		'profile' : profile,
		'message' : message,
	}
	return render_to_response('panel/panel_message_sent.html', context,  context_instance = RequestContext(request))
@login_required
def MessageSend(request, user_name):
	if not request.user.is_staff:
		if (request.user.username != user_name):
			return HttpResponseRedirect('http://fblaconnection.com/panel/' + request.user.username + '/')
	try:
		user = User.objects.get(username=user_name)
	except User.DoesNotExist:
		return HttpResponseRedirect('http://fblaconnection.com/panel/'+ request.user.username + '/')
	profile = user.get_profile()
	context = {
		'user' : user,
		'profile' : profile,
	}
	if request.GET:
		if request.GET.get('user'):
			message_user = request.GET['user']
		else:
			message_user = None
		if request.GET.get('message_id'):
			message_rep_id = request.GET['message_id']
			try:
				message_rep = Message.objects.get(pk=message_rep_id)
			except Message.DoesNotExist:
				return HttpResponseRedirect('http://fblaconnection.com/panel/'+ request.user.username + '/')
			if not request.user.is_staff:
				if (message_rep.reciever != request.user):
					return HttpResponseRedirect('http://fblaconnection.com/panel/'+ request.user.username + '/')
				elif (message_rep.sender != request.user):
					return HttpResponseRedirect('http://fblaconnection.com/panel/'+ request.user.username + '/')
		else:
			message_rep = None
	else:
		message_user = None
		message_rep = None
	context.update({
		'message_user' : message_user,
		'message_rep' : message_rep,
	})
	if request.POST:
		#Errors
		errors = False
		reciever_error = False
		content_error = False
		subject_error = False
		#End Errors
		reciever = request.POST['reciever']
		subject = request.POST['subject']
		content = request.POST['content']
		try:
			rec = User.objects.get(username=reciever)
		except User.DoesNotExist:
			reciever_error = True
			errors = True
		if (reciever == ""):
			reciever_error = True
			errors = True
		if (subject == ""):
			subject_error = True
			errors = True
		if (content == ""):
			content_error = True
			errors = True
		if errors:
			context.update({
				'errors' : errors,
				'reciever' : reciever,
				'subject' : subject,
				'content' : content,
				'reciever_error' : reciever_error,
				'content_error' : content_error,
				'subject_error' : subject_error,
			})
			return render_to_response('panel/panel_message_send.html', context,  context_instance = RequestContext(request))
		else:
			message = Message(sender=user, reciever=rec, subject=subject, date_sent=datetime.now(), content=content)
			message.save()
			success = True
			context.update({
				'success' : success,
			})
	return render_to_response('panel/panel_message_send.html', context,  context_instance = RequestContext(request))
@login_required
def MessageViewFull(request, user_name, message_id):
	if not request.user.is_staff:
		if (request.user.username != user_name):
			return HttpResponseRedirect('http://fblaconnection.com/panel/' + request.user.username + '/')
	try:
		user = User.objects.get(username=user_name)
	except User.DoesNotExist:
		return HttpResponseRedirect('http://fblaconnection.com/panel/'+ request.user.username + '/')
	message = Message.objects.get(pk=message_id)
	if (message.reciever != request.user):
		errors = True
		if (message.sender != request.user):
			errors = True
		else:
			errors = False
	else:
		errors = False
	if errors:
		return HttpResponseRedirect('http://fblaconnection.com/panel/'+ request.user.username + '/')
	context = {
		'user' : user,
		'message' : message,
	}
	if (request.user == message.reciever):
		rec = True
		context.update({
			'rec' : rec,
		})
	return render_to_response('panel/panel_message_view.html', context,  context_instance = RequestContext(request))
@login_required
def MessageDelete(request, user_name, message_id):
	if not request.user.is_staff:
		if (request.user.username != user_name):
			return HttpResponseRedirect('http://fblaconnection.com/panel/' + request.user.username + '/')
	try:
		user = User.objects.get(username=user_name)
	except User.DoesNotExist:
		return HttpResponseRedirect('http://fblaconnection.com/panel/'+ request.user.username + '/')
	try:
		message = Message.objects.get(pk=message_id)
	except Message.DoesNotExist:
		return HttpResponseRedirect('http://fblaconnection.com/panel/'+ request.user.username + '/')
	errors = False
	if not request.user.is_staff:
		if (message.reciever != request.user):
			errors = True
	if errors:
		return HttpResponseRedirect('http://fblaconnection.com/panel/'+ request.user.username + '/')
	else:
		message.delete()
		return HttpResponseRedirect('http://fblaconnection.com/panel/'+ request.user.username + '/messages/recieved/')
@login_required
def DeleteBulk(request, user_name):
	if not request.user.is_staff:
		if (request.user.username != user_name):
			return HttpResponseRedirect('http://fblaconnection.com/panel/' + request.user.username + '/')
	try:
		user = User.objects.get(username=user_name)
	except User.DoesNotExist:
		return HttpResponseRedirect('http://fblaconnection.com/panel/'+ request.user.username + '/')
	if request.POST:
		post = request.POST
		for posts in post:
			if (posts != 'delete'):
				messages = Message.objects.filter(pk=posts)
				messages.delete()
		return HttpResponseRedirect('http://fblaconnection.com/panel/'+ request.user.username + '/messages/recieved/')
	return HttpResponseRedirect('http://fblaconnection.com/panel/'+ request.user.username + '/messages/recieved/')
@login_required
def Events(request):
	ev = True
	context = {
		'ev' : ev,
	}
	return render_to_response('panel/panel_events.html', context,  context_instance = RequestContext(request))
@login_required
def SponsorShip(request):
	ev = True
	context = {
		'ev' : ev,
	}
	return render_to_response('panel/panel_spons.html', context,  context_instance = RequestContext(request))
@login_required
def PublicProfile(request, user_name):
	try:
		user = User.objects.get(username=user_name)
	except User.DoesNotExist:
		return HttpResponseRedirect('http://fblaconnection.com/panel/'+ request.user.username + '/')
	profile = user.get_profile()
	about = profile.about
	aim = profile.aim
	yahoo = profile.yahoo
	msn = profile.msn
	site = profile.site
	site_en = True
	if (about == ""):
		about = "Not availiable for this user."
	if (aim == "" or aim == "Your AIM (optional)"):
		aim = "Not availiable for this user."
	if (yahoo == "" or yahoo == "Your YAHOO (optional)"):
		yahoo = "Not availiable for this user."
	if (msn == "" or msn == "Your MSN (optional)"):
		msn = "Not availiable for this user."
	if (site == "" or site == "Your Website (optional)"):
		site = "Not availiable for this user."
		site_en = False
	context = {
		'user' : user,
		'profile' : profile,
		'about' : about,
		'aim' : aim,
		'yahoo' : yahoo,
		'msn' : msn,
		'site' : site,
		'site_en' : site_en,
	}
	return render_to_response('panel/panel_userp.html', context,  context_instance = RequestContext(request))
@login_required
def Follow(request, user_name):
	user = get_object_or_404(User, username=user_name)
	profile = user.get_profile()
	context = {
		'user' : user,
		'profile' : profile,
	}
	if request.GET:
		if request.GET.get('ex'):
			ex = request.GET['ex']
			if request.GET.get('user'):
				user_get = request.GET['user']
				user_to = get_object_or_404(User, username=user_get)
				if (ex == "follow"):
					ul, created = UserLink.objects.get_or_create(from_user=request.user, 
				        	to_user=user_to)
					return HttpResponseRedirect('http://fblaconnection.com/panel/' + request.user.username + '/socialgraph/')
				elif (ex == "unfollow"):
					try:
						ul = UserLink.objects.get(from_user=request.user, to_user=user_to)
						ul.delete()
						deleted = True
					except UserLink.DoesNotExist:
						deleted = False
					return HttpResponseRedirect('http://fblaconnection.com/panel/' + request.user.username + '/socialgraph/')
			else:
				return HttpResponseRedirect('http://fblaconnection.com/panel/' + request.user.username + '/socialgraph/')
@login_required
def ViewFollowers(request, user_name):
	if not request.user.is_staff:
		if (request.user.username != user_name):
			return HttpResponseRedirect('http://fblaconnection.com/panel/' + request.user.username + '/')
	user = get_object_or_404(User, username=user_name)
	profile = user.get_profile()
	context = {
		'user' : user,
		'profile' : profile,
	}
	following = get_people_following_user(user)
	context.update({
		'following' : following,
	})
	return render_to_response('panel/socialgraph_view_followers.html', context,  context_instance = RequestContext(request))
@login_required
def ViewFollowing(request, user_name):
	if not request.user.is_staff:
		if (request.user.username != user_name):
			return HttpResponseRedirect('http://fblaconnection.com/panel/' + request.user.username + '/')
	user = get_object_or_404(User, username=user_name)
	profile = user.get_profile()
	context = {
		'user' : user,
		'profile' : profile,
	}
	following = get_people_user_follows(user)
	context.update({
		'following' : following,
	})
	return render_to_response('panel/socialgraph_view.html', context,  context_instance = RequestContext(request))
@login_required
def Search(request):
	user = get_object_or_404(User, id=request.user.id)
	profile = user.get_profile()
	context = {
		'user' : user,
		'profile' : profile,
	}
	query_string = ''
	found_entries = None
	search = False
	if request.GET:
		if request.GET.get('q'):
			query_string = request.GET['q']
			if request.GET.get('by'):
				by = request.GET['by']
				if (by == "1"):
					entry_query = get_query(query_string, ['first_name',])
				if (by == "2"):
					entry_query = get_query(query_string, ['last_name',])
				if (by == "3"):
					entry_query = get_query(query_string, ['email',])
				found_entries = User.objects.filter(entry_query).order_by('-first_name')
				context.update({
					'by' : by,
				})
		if (query_string == "" or query_string == "Search...."):
			search = False
		else:
			search = True
		context.update({
			'search' : search,
			'query_string': query_string, 
			'found_entries': found_entries,
		})

	return render_to_response('panel/panel_search.html', context,  context_instance = RequestContext(request))
@login_required
def Panel_index(request, user_name):
	if not request.user.is_staff:
		if (request.user.username != user_name):
			return HttpResponseRedirect('http://fblaconnection.com/panel/' + request.user.username + '/')
	user = User.objects.get(username=user_name)
	ugallery = UserGallery.objects.get(pk=1)
	profile = user.get_profile()
	context = {
		'user' : user,
		'profile' : profile,
		'ugallery' : ugallery,
	}
	return render_to_response('panel/panel_index.html', context, context_instance = RequestContext(request))
@login_required
def Profile(request, user_name):
	if not request.user.is_staff:
		if (request.user.username != user_name):
			return HttpResponseRedirect('http://fblaconnection.com/panel/'+ request.user.username + '/')
	user = User.objects.get(username=user_name)
	profile = user.get_profile()
	context = {
		'user' : user,
		'profile' : profile,
	}
	if request.POST:
		about = request.POST['about']
		email = request.POST['email']
		grade = request.POST['grade']
		gender = request.POST['gender']
		site = request.POST['site']
		aim = request.POST['aim']
		msn = request.POST['msn']
		yahoo = request.POST['yahoo']
		success = False
		#Error Values
		errors = False
		email_mult = True
		email_re_error = False
		if (email != user.email):
			try:
				user = User.objects.get(email=email)
			except User.DoesNotExist:
				email_mult = False
		else:
			email_mult = False
		if (email_mult == True):
			errors = True
		if not email_re.match(email):
			errors = True
			email_re_error = True
		context.update({
			'about' : about,
			'email' : email,
			'grade' : grade,
			'gender' : gender,
			'site' : site,
			'aim' : aim,
			'msn' : msn,
			'yahoo' : yahoo,
			'errors' : errors,
			'email_mult' : email_mult,
			'email_re_error' : email_re_error,
		})
		if errors:
			return render_to_response('panel/panel_profile.html', context, context_instance = RequestContext(request))
		else:
			user.email = email
			user.save()
			#profile stuff
			profile.grade = grade
			profile.gender = gender
			profile.about = about
			profile.site = site
			profile.aim = aim
			profile.msn = msn
			profile.yahoo = yahoo
			profile.save()
			#profile stuff
			success = True
			user = User.objects.get(username=user_name)
			profile = user.get_profile()
			context.update({
				'success' : success,
				'user' : user,
				'profile' : profile,
			})
			return render_to_response('panel/panel_profile.html', context, context_instance = RequestContext(request))
	return render_to_response('panel/panel_profile.html', context, context_instance = RequestContext(request))
	
def Redirect(request):
	if (request.user.is_authenticated()):
		return HttpResponseRedirect('http://fblaconnection.com/panel/'+ request.user.username + '/')
	else: 
		return HttpResponseRedirect('http://fblaconnection.com/register/')
